package com.iqik.rpc.boot;

import com.iqik.rpc.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

public class Server {

    private ServerBootstrap serverBootstrap;
    private ChannelFuture future = null;
    private NioEventLoopGroup bossLoop;
    private NioEventLoopGroup workLoop;
    private RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    private CuratorFramework client;
    private String path = "/server";
    private String address;

    public Server build() {
        // 1. 创建线程池对象
        bossLoop = new NioEventLoopGroup();
        workLoop = new NioEventLoopGroup();

        // 2. 创建启动引导类对象
        serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossLoop, workLoop)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new ServerHandler());
                    }
                });
        client = CuratorFrameworkFactory.builder()
                .connectString("132.232.16.135:2181")
                .sessionTimeoutMs(50000)
                .connectionTimeoutMs(30000)
                .retryPolicy(retryPolicy)
                .namespace("base") // 独立的命名空间 在/base目录下
                .build();
        client.start();
        return this;
    }

    public void start(String host, int port) throws Exception {
        this.address = String.format("%s:%d", host, port);
        this.future = this.serverBootstrap.bind(host, port).sync();
        if (this.future.isSuccess()) {

            client.create()
                    .creatingParentContainersIfNeeded()
                    .withMode(CreateMode.EPHEMERAL)
                    .forPath(String.format("%s/%s", path, address));
        }
    }

    public void stop() throws Exception {
        if (this.future != null) {
            if (this.future.isSuccess()) {
                this.future.channel().close().sync();
                this.workLoop.shutdownGracefully().sync();
                this.bossLoop.shutdownGracefully().sync();
                this.future = null;
                this.serverBootstrap = null;
                this.workLoop = null;
                this.bossLoop = null;
                this.retryPolicy = null;
                this.client.close();
            }
        }
    }

    public static Server server1() throws Exception {
        Server server = new Server().build();
        server.start("127.0.0.1", 8081);
        return server;
    }

    public static Server server2() throws Exception {
        Server server2 = new Server().build();
        server2.start("127.0.0.1", 8082);
        return server2;
    }

    public static void main(String[] args) throws Exception {
        Server server1 = server1();
        System.out.println("启动注册 server 127.0.0.1:8081");
//        Thread.sleep(5000);
//        Server server2 = server2();
//        System.out.println("启动注册 server 127.0.0.1:8082");
//        Thread.sleep(50000);
//        server1.stop();
//        System.out.println("关闭 server 127.0.0.1:8081");
    }
}
